In C++, a struct is a composite data type that groups together variables of different data types under a single name. Structs are similar to classes, but they have some differences in terms of default member access, and they are often used for simple data structures where all members are public by default. Here's how define and use a struct in C++:
To define a struct, use the struct keyword followed by the struct's name and a pair of curly braces { } to enclose the member variables. Each member variable is declared with a data type and a name, and the members are separated by semicolons.
// Define a struct named 'Person'
struct Person {
std::string name;
int age;
double height;
};
In this example, we've defined a struct called Person with three members: name, age, and height.
it can create objects (instances) of a struct in the same way create objects of a class. Simply specify the struct's name, followed by the object's name and optionally initialize its members:
// Create a Person object and initialize its members
Person person1;
person1.name = "Alice";
person1.age = 30;
person1.height = 1.75;
it can access the members of a struct using the dot . operator:
std::cout << "Name: " << person1.name << std::endl;
std::cout << "Age: " << person1.age << std::endl;
std::cout << "Height: " << person1.height << std::endl;
C++ allows to initialize struct objects during declaration:
Person person2 = {"Bob", 25, 1.80};
it can pass struct objects as function parameters just like any other data type:
void printPersonInfo(const Person& person) {
std::cout << "Name: " << person.name << std::endl;
std::cout << "Age: " << person.age << std::endl;
std::cout << "Height: " << person.height << std::endl;
}
In C++, both structs and classes it can be used to create user-defined data types, but they have different default member access levels. In structs, all members are public by default, while in classes, members are private by default. However, it can explicitly specify access modifiers in both structs and classes. The choice between using a struct or a class depends on the design and intended usage of data structure. If need encapsulation and private members, classes might be a better choice. If have a simple data structure without much behavior and all members are public, a struct might be more appropriate.
question
question2